//
//  VideoRecorderViewController.swift
//  test
//
//  Created by bianruifeng on 2025/7/5.
//


import UIKit
import AVFoundation
import Photos
import SnapKit
import RxSwift
enum MyError: Error {
    case endError(message: String)
}
class VideoRecorderViewController: UIViewController, AVCaptureFileOutputRecordingDelegate {
    private let viewModel = CountdownViewModel()
    // 捕获会话
    var captureSession: AVCaptureSession!
    // 视频输出
    var movieOutput: AVCaptureMovieFileOutput!
    // 视频预览层
    var previewLayer: AVCaptureVideoPreviewLayer!
    // 录制按钮
    var recordButton: UIButton!
    // 是否正在录制
    var isRecording = false
    
    // 创建 UITableView
    private lazy var tableView: UITableView = {
        let tableView = UITableView()
        tableView.backgroundColor = .systemGroupedBackground
        tableView.separatorStyle = .singleLine
        tableView.rowHeight = 60
        tableView.delegate = self
        tableView.dataSource = self
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
        return tableView
    }()
    
    private lazy var play = UIView()
    private lazy var countdown = UILabel()
    
    let disposeBag = DisposeBag()

    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = .white
        // 权限
        checkCameraPermission()
        
        // 表格
        setupTableView()
        // 视频
        setupUI()
        // 倒计时
        // 订阅倒计时
        viewModel.countdownObservable.observe(on: MainScheduler.instance)
            .subscribe(onNext: { timeLeft in
                if timeLeft==6{
                    self.countdown.text = "开始录制"
                    self.startRecording()
                }
                if timeLeft==1{
                    self.countdown.text = "保存"
                    self.stopRecording()
                }
                
                if timeLeft==30{
                    self.recordButton.setTitle("正在监控", for: .normal)
                }
                
                self.countdown.text = String(timeLeft)
            })
            .disposed(by: disposeBag)
        
        
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        if captureSession?.isRunning == false {
            DispatchQueue.global(qos: .userInitiated).async { [weak self] in
                self?.captureSession.startRunning()
            }
        }
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        viewModel.stopCountdown() // 停止倒计时
        if captureSession?.isRunning == true {
            captureSession.stopRunning()
        }
    }
    
    // 检查相机权限
    func checkCameraPermission() {
        let status = AVCaptureDevice.authorizationStatus(for: .video)
        
        switch status {
        case .authorized:
            setupCamera()
        case .notDetermined:
            AVCaptureDevice.requestAccess(for: .video) { granted in
                if granted {
                    DispatchQueue.main.async {
                        self.setupCamera()
                    }
                }
            }
        case .denied, .restricted:
            showPermissionAlert()
        @unknown default:
            break
        }
    }
    
    // 设置相机
    func setupCamera() {
        captureSession = AVCaptureSession()
        captureSession.sessionPreset = .high
        
        // 获取前置摄像头
        guard let frontCamera = AVCaptureDevice.default(.builtInWideAngleCamera,
                                                        for: .video,
                                                        position: .front) else {
            print("无法获取前置摄像头")
            return
        }
        
        // 获取麦克风
        guard let audioDevice = AVCaptureDevice.default(for: .audio) else {
            print("无法获取麦克风")
            return
        }
        
        do {
            // 视频输入
            let videoInput = try AVCaptureDeviceInput(device: frontCamera)
            // 音频输入
            let audioInput = try AVCaptureDeviceInput(device: audioDevice)
            
            // 添加到会话
            if captureSession.canAddInput(videoInput) {
                captureSession.addInput(videoInput)
            }
            
            if captureSession.canAddInput(audioInput) {
                captureSession.addInput(audioInput)
            }
            
            // 设置视频输出
            movieOutput = AVCaptureMovieFileOutput()
            if captureSession.canAddOutput(movieOutput) {
                captureSession.addOutput(movieOutput)
            }
            
            // 设置预览层
            previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
            previewLayer.videoGravity = .resizeAspectFill
            previewLayer.connection?.videoOrientation = .portrait
            previewLayer.frame = CGRectMake(0, 0, 150, 200)
            //            view.layer.insertSublayer(previewLayer, at: 999)
            
            play.layer.insertSublayer(previewLayer, at: 999)
            
            
            
            // 开始会话
            DispatchQueue.global(qos: .userInitiated).async { [weak self] in
                self?.captureSession.startRunning()
            }
            
        } catch {
            print("错误: \(error.localizedDescription)")
        }
    }
    
    // 设置UI
    func setupUI() {
        // 视频容器
        view.addSubview(play)
        view.bringSubviewToFront(play)
        play.backgroundColor = .gray
        play.layer.cornerRadius = 10
        play.layer.masksToBounds = true
        play.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(80)
            make.left.equalToSuperview().offset(20)
            make.size.equalTo(CGSize(width: 150, height: 200))
        }
        countdown.textAlignment = .center
        view.addSubview(countdown)
        view.bringSubviewToFront(countdown)
        countdown.backgroundColor = .red
        countdown.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(80)
            make.left.equalTo(play.snp.right).offset(20)
            make.size.equalTo(CGSize(width: 100, height: 50))
        }
        
        
        // 录制按钮
        recordButton = UIButton(type: .custom)
        recordButton.setTitle("正在监控", for: .normal)
        recordButton.backgroundColor = .red
        view.addSubview(recordButton)
        recordButton.snp.makeConstraints { make in
            make.top.equalTo(countdown.snp.bottom)
            make.left.equalTo(countdown)
            make.width.equalTo(countdown.snp.width)
            make.height.equalTo(40)
        }
    }
    
    // 开始/停止录制
    @objc func toggleRecording() {
        if isRecording {
            stopRecording()
        } else {
            startRecording()
        }
    }
    
    // 开始录制
    func startRecording() {
        guard let connection = movieOutput.connection(with: .video) else { return }
        
        if connection.isVideoOrientationSupported {
            connection.videoOrientation = .portrait
        }
        
        if connection.isVideoMirroringSupported {
            connection.isVideoMirrored = true // 前置摄像头需要镜像
        }
        
        let outputFileName = NSUUID().uuidString
        let outputFilePath = (NSTemporaryDirectory() as NSString).appendingPathComponent("\(outputFileName).mov")
        let outputURL = URL(fileURLWithPath: outputFilePath)
        
        movieOutput.startRecording(to: outputURL, recordingDelegate: self)
        
        isRecording = true
        recordButton.backgroundColor = UIColor.red.withAlphaComponent(0.5)
        recordButton.setTitle("正在录制", for: .normal)
        
    }
    
    // 停止录制
    func stopRecording() {
        movieOutput.stopRecording()
        isRecording = false
        recordButton.backgroundColor = .red
        recordButton.setTitle("正在保存", for: .normal)
        
    }
    
    // 保存视频到相册
    func saveVideoToLibrary(_ videoURL: URL) {
        PHPhotoLibrary.requestAuthorization { status in
            if status == .authorized {
                PHPhotoLibrary.shared().performChanges({
                    PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: videoURL)
                }) { saved, error in
                    DispatchQueue.main.async {
                        if saved {
                            let alert = UIAlertController(title: "视频已保存", message: "视频已成功保存到相册", preferredStyle: .alert)
                            alert.addAction(UIAlertAction(title: "OK", style: .default))
                            self.present(alert, animated: true)
                            
                            // 删除临时文件
                            try? FileManager.default.removeItem(at: videoURL)
                        } else if let error = error {
                            print("保存视频出错: \(error.localizedDescription)")
                        }
                    }
                }
            }
        }
    }
    
    // 显示权限提示
    func showPermissionAlert() {
        let alert = UIAlertController(
            title: "需要权限",
            message: "请在设置中启用相机和麦克风权限以使用此功能",
            preferredStyle: .alert
        )
        
        alert.addAction(UIAlertAction(title: "取消", style: .default))
        alert.addAction(UIAlertAction(title: "去设置", style: .cancel) { _ in
            if let url = URL(string: UIApplication.openSettingsURLString) {
                UIApplication.shared.open(url)
            }
        })
        
        present(alert, animated: true)
    }
    
    // MARK: - AVCaptureFileOutputRecordingDelegate
    
    func fileOutput(_ output: AVCaptureFileOutput,
                    didStartRecordingTo fileURL: URL,
                    from connections: [AVCaptureConnection]) {
        print("开始录制: \(fileURL)")
    }
    
    func fileOutput(_ output: AVCaptureFileOutput,
                    didFinishRecordingTo outputFileURL: URL,
                    from connections: [AVCaptureConnection],
                    error: Error?) {
        if let error = error {
            print("录制错误: \(error.localizedDescription)")
            return
        }
        
        print("录制完成: \(outputFileURL)")
        saveVideoToLibrary(outputFileURL)
    }
}


extension VideoRecorderViewController{
    private func setupTableView() {
        view.backgroundColor = .white
        
        // 添加 tableView 到视图
        view.addSubview(tableView)
        
        // 使用 SnapKit 设置约束
        tableView.snp.makeConstraints { make in
            make.top.equalTo(view.safeAreaLayoutGuide.snp.top)
            make.left.right.bottom.equalToSuperview()
        }
    }
}
// MARK: - UITableViewDataSource
extension VideoRecorderViewController: UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 20
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
        
        // 配置 cell
        cell.textLabel?.text = String(indexPath.row)
        cell.imageView?.image = UIImage(systemName: "circle.fill")
        cell.imageView?.tintColor = .systemOrange
        cell.accessoryType = .disclosureIndicator
        
        return cell
    }
}

// MARK: - UITableViewDelegate
extension VideoRecorderViewController: UITableViewDelegate {
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        print("Selected: \(indexPath.row)")
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 55
    }
}

extension VideoRecorderViewController{
    
}
